<template>
  <div class="course-qualification-container">
    <a-tabs :defaultActiveKey="$hasPer(['teacher','bzr'])?'1':'3'" @change="handleTabChange">
      <a-tab-pane tab="课程资格申请" key="1" v-if="$hasPer(['teacher','bzr'])">
        <div class="tab-content">
          <a-alert
            message="课程资格申请说明"
            description="请填写您希望申请授课资格的课程信息，提交后等待审核。"
            type="info"
            showIcon
            style="margin-bottom: 20px"
          />
          
          <a-form :form="form" @submit="handleSubmit">
            <a-form-item label="教师姓名" :labelCol="{ span: 4 }" :wrapperCol="{ span: 12 }">
              <a-input
                v-decorator="[
                  'teacherName',
                  { rules: [{ required: true, message: '请输入教师姓名' }] }
                ]"
                placeholder="请输入您的姓名"
              />
            </a-form-item>
            
            <a-form-item label="工号" :labelCol="{ span: 4 }" :wrapperCol="{ span: 12 }">
              <a-input
                v-decorator="[
                  'teacherId',
                  { rules: [{ required: true, message: '请输入工号' }] }
                ]"
                placeholder="请输入您的工号"
              />
            </a-form-item>
            
            <a-form-item label="所属院系" :labelCol="{ span: 4 }" :wrapperCol="{ span: 12 }">
              <a-select
                v-decorator="[
                  'department',
                  { rules: [{ required: true, message: '请选择所属院系' }] }
                ]"
                placeholder="请选择所属院系"
              >
                <a-select-option value="computer">信息工程系</a-select-option>
                <a-select-option value="math">机电工程系</a-select-option>
                <a-select-option value="physics">建筑工程系</a-select-option>
                <a-select-option value="chemistry">化学学院</a-select-option>
                <a-select-option value="literature">文学院</a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item label="申请课程" :labelCol="{ span: 4 }" :wrapperCol="{ span: 12 }">
              <a-select
                v-decorator="[
                  'course',
                  { rules: [{ required: true, message: '请选择申请课程' }] }
                ]"
                placeholder="请选择申请课程"
                showSearch
                optionFilterProp="children"
              >
                <a-select-option value="cs101">计算机科学导论 (CS101)</a-select-option>
                <a-select-option value="math201">高等数学（上）	 (MATH201)</a-select-option>
                <a-select-option value="phy301">量子力学 (PHY301)</a-select-option>
                <a-select-option value="chem401">有机化学 (CHEM401)</a-select-option>
                <a-select-option value="lit501">现代文学 (LIT501)</a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item label="授课经历" :labelCol="{ span: 4 }" :wrapperCol="{ span: 12 }">
              <a-textarea
                v-decorator="[
                  'experience',
                  { rules: [{ required: true, message: '请输入相关授课经历' }] }
                ]"
                placeholder="请描述您相关的授课经历"
                :rows="4"
              />
            </a-form-item>
            
            <a-form-item label="相关资质" :labelCol="{ span: 4 }" :wrapperCol="{ span: 12 }">
              <a-upload
                v-decorator="[
                  'qualifications',
                  { valuePropName: 'fileList', getValueFromEvent: normFile }
                ]"
                name="file"
                :multiple="true"
                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                @change="handleUploadChange"
              >
                <a-button> <a-icon type="upload" /> 上传资质文件 </a-button>
              </a-upload>
            </a-form-item>
            
            <a-form-item :wrapperCol="{ span: 12, offset: 4 }">
              <a-button type="primary" htmlType="submit">提交申请</a-button>
              <a-button style="margin-left: 10px" @click="handleReset">重置</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-tab-pane>
      
      <a-tab-pane tab="申请状态查询" key="2" v-if="$hasPer(['teacher','bzr'])">
        <div class="tab-content">
          <a-alert
            message="申请状态查询"
            description="您可以在此查看已提交的课程资格申请状态。"
            type="info"
            showIcon
            style="margin-bottom: 20px"
          />
          
          <a-table
            :columns="statusColumns"
            :dataSource="statusData"
            :pagination="{ pageSize: 5 }"
            rowKey="id"
          >
            <span slot="status" slot-scope="status">
              <a-tag :color="status === 'approved' ? 'green' : status === 'rejected' ? 'red' : 'orange'">
                {{ status === 'approved' ? '已通过' : status === 'rejected' ? '已拒绝' : '审核中' }}
              </a-tag>
            </span>
            
            <span slot="action" slot-scope="record">
              <a @click="handleViewDetail(record)">查看详情</a>
              <a-divider type="vertical" />
              <a v-if="record.status === 'rejected'" @click="handleReapply(record)">重新申请</a>
            </span>
          </a-table>
          
          <a-modal
            title="申请详情"
            :visible="detailVisible"
            @ok="handleDetailOk"
            @cancel="handleDetailCancel"
          >
            <div v-if="currentDetail">
              <p><strong>课程名称：</strong>{{ currentDetail.courseName }}</p>
              <p><strong>申请时间：</strong>{{ currentDetail.applyTime }}</p>
              <p><strong>审核状态：</strong>
                <a-tag :color="currentDetail.status === 'approved' ? 'green' : currentDetail.status === 'rejected' ? 'red' : 'orange'">
                  {{ currentDetail.status === 'approved' ? '已通过' : currentDetail.status === 'rejected' ? '已拒绝' : '审核中' }}
                </a-tag>
              </p>
              <p v-if="currentDetail.status === 'rejected'"><strong>拒绝原因：</strong>{{ currentDetail.rejectReason }}</p>
              <p><strong>授课经历：</strong>{{ currentDetail.experience }}</p>
            </div>
          </a-modal>
        </div>
      </a-tab-pane>
      
      <a-tab-pane tab="审核管理" key="3" v-if="$hasPer(['system'])">
        <div class="tab-content">
          <a-alert
            message="审核管理"
            description="您可以在此审核教师提交的课程资格申请。"
            type="info"
            showIcon
            style="margin-bottom: 20px"
          />
          
          <a-table
            :columns="reviewColumns"
            :dataSource="reviewData"
            :pagination="{ pageSize: 5 }"
            rowKey="id"
          >
            <span slot="status" slot-scope="status">
              <a-tag :color="status === 'approved' ? 'green' : status === 'rejected' ? 'red' : 'orange'">
                {{ status === 'approved' ? '已通过' : status === 'rejected' ? '已拒绝' : '待审核' }}
              </a-tag>
            </span>
            
            <span slot="action" slot-scope="record">
              <a-button-group>
                <a-button type="primary" size="small" @click="handleApprove(record)">通过</a-button>
                <a-button size="small" @click="handleReject(record)">拒绝</a-button>
                <a-button size="small" @click="handleViewApplication(record)">查看</a-button>
              </a-button-group>
            </span>
          </a-table>
          
          <a-modal
            title="审核申请"
            :visible="reviewModalVisible"
            @ok="handleReviewModalOk"
            @cancel="handleReviewModalCancel"
            width="800px"
          >
            <div v-if="currentApplication">
              <a-descriptions bordered :column="2">
                <a-descriptions-item label="教师姓名">{{ currentApplication.teacherName }}</a-descriptions-item>
                <a-descriptions-item label="工号">{{ currentApplication.teacherId }}</a-descriptions-item>
                <a-descriptions-item label="所属院系">{{ currentApplication.department }}</a-descriptions-item>
                <a-descriptions-item label="申请课程">{{ currentApplication.courseName }}</a-descriptions-item>
                <a-descriptions-item label="申请时间" :span="2">{{ currentApplication.applyTime }}</a-descriptions-item>
                <a-descriptions-item label="授课经历" :span="2">
                  {{ currentApplication.experience }}
                </a-descriptions-item>
                <a-descriptions-item label="资质文件" :span="2">
                  <a-list
                    :dataSource="currentApplication.qualifications"
                    itemLayout="horizontal"
                  >
                    <a-list-item slot="renderItem" slot-scope="item">
                      <a-list-item-meta>
                        <a slot="title" :href="item.url" target="_blank">{{ item.name }}</a>
                        <a-icon slot="avatar" type="file" />
                      </a-list-item-meta>
                    </a-list-item>
                  </a-list>
                </a-descriptions-item>
              </a-descriptions>
              
              <a-form v-if="reviewAction" :form="reviewForm" style="margin-top: 20px">
                <a-form-item v-if="reviewAction === 'reject'" label="拒绝原因" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18 }">
                  <a-textarea
                    v-decorator="[
                      'rejectReason',
                      { rules: [{ required: true, message: '请输入拒绝原因' }] }
                    ]"
                    placeholder="请输入拒绝原因"
                    :rows="3"
                  />
                </a-form-item>
              </a-form>
            </div>
          </a-modal>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
export default {
  beforeCreate() {
    this.form = this.$form.createForm(this);
    this.reviewForm = this.$form.createForm(this);
  },
  
  data() {
    return {
      isAdmin: true, // 模拟管理员身份
      activeKey: '1',
      detailVisible: false,
      reviewModalVisible: false,
      currentDetail: null,
      currentApplication: null,
      reviewAction: null, // 'approve' or 'reject'
      
      // 申请状态表格列
      statusColumns: [
        {
          title: '课程名称',
          dataIndex: 'courseName',
          key: 'courseName',
        },
        {
          title: '申请时间',
          dataIndex: 'applyTime',
          key: 'applyTime',
        },
        {
          title: '审核状态',
          dataIndex: 'status',
          key: 'status',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      
      // 申请状态数据
      statusData: [
        {
          id: '1',
          courseName: '计算机科学导论 (CS101)',
          applyTime: '2024-05-10 14:30',
          status: 'approved',
          experience: '曾在XX大学担任计算机导论课程助教2年',
          rejectReason: '',
        },
        {
          id: '2',
          courseName: '量子力学 (PHY301)',
          applyTime: '2024-05-15 09:15',
          status: 'rejected',
          experience: '自学量子力学相关知识',
          rejectReason: '缺乏相关教学经验',
        },
        {
          id: '3',
          courseName: '现代文学 (LIT501)',
          applyTime: '2024-05-20 16:45',
          status: 'pending',
          experience: '发表过多篇文学评论文章',
          rejectReason: '',
        },
      ],
      
      // 审核管理表格列
      reviewColumns: [
        {
          title: '教师姓名',
          dataIndex: 'teacherName',
          key: 'teacherName',
        },
        {
          title: '工号',
          dataIndex: 'teacherId',
          key: 'teacherId',
        },
        {
          title: '申请课程',
          dataIndex: 'courseName',
          key: 'courseName',
        },
        {
          title: '申请时间',
          dataIndex: 'applyTime',
          key: 'applyTime',
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      
      // 审核管理数据
      reviewData: [
        {
          id: '1',
          teacherName: '王芳',
          teacherId: 'T1001',
          department: '信息工程系',
          courseName: '数据结构 (CS201)',
          applyTime: '2024-05-18 10:20',
          status: 'pending',
          experience: '曾在XX公司担任软件开发工程师，有丰富的数据结构实践经验',
          qualifications: [
            { name: '教师资格证.pdf', url: '#' },
            { name: '计算机等级证书.jpg', url: '#' },
          ],
        },
        {
          id: '2',
          teacherName: '李廷',
          teacherId: 'T1002',
          department: '机电工程系',
          courseName: '离散数学 (MATH301)',
          applyTime: '2024-05-19 14:35',
          status: 'pending',
          experience: '教授离散数学课程3年，编写过相关教材',
          qualifications: [
            { name: '教师资格证.pdf', url: '#' },
            { name: '博士学位证书.jpg', url: '#' },
          ],
        },
        {
          id: '3',
          teacherName: '王雪',
          teacherId: 'T1003',
          department: '建筑工程系',
          courseName: '电磁学 (PHY202)',
          applyTime: '2024-05-20 09:10',
          status: 'pending',
          experience: '发表过多篇电磁学领域论文',
          qualifications: [
            { name: '教师资格证.pdf', url: '#' },
            { name: '研究成果列表.pdf', url: '#' },
          ],
        },
      ],
    };
  },
  
  methods: {
    handleTabChange(key) {
      this.activeKey = key;
    },
    
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values);
          this.$message.success('申请提交成功！');
          this.form.resetFields();
          
          // 模拟添加到申请状态列表
          this.statusData.unshift({
            id: Date.now().toString(),
            courseName: this.getCourseName(values.course),
            applyTime: new Date().toLocaleString(),
            status: 'pending',
            experience: values.experience,
            rejectReason: '',
          });
        }
      });
    },
    
    handleReset() {
      this.form.resetFields();
    },
    
    normFile(e) {
      console.log('Upload event:', e);
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    },
    
    handleUploadChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} 文件上传成功`);
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败`);
      }
    },
    
    handleViewDetail(record) {
      this.currentDetail = record;
      this.detailVisible = true;
    },
    
    handleDetailOk() {
      this.detailVisible = false;
    },
    
    handleDetailCancel() {
      this.detailVisible = false;
    },
    
    handleReapply(record) {
      this.$confirm({
        title: '确认重新申请?',
        content: '您确定要重新申请该课程的教学资格吗?',
        onOk: () => {
          this.$message.success('已提交重新申请');
          // 在实际应用中，这里会调用API
          record.status = 'pending';
        },
        onCancel() {},
      });
    },
    
    handleApprove(record) {
      this.reviewAction = 'approve';
      this.currentApplication = record;
      this.reviewModalVisible = true;
    },
    
    handleReject(record) {
      this.reviewAction = 'reject';
      this.currentApplication = record;
      this.reviewModalVisible = true;
      this.$nextTick(() => {
        this.reviewForm.setFieldsValue({ rejectReason: '' });
      });
    },
    
    handleViewApplication(record) {
      this.reviewAction = null;
      this.currentApplication = record;
      this.reviewModalVisible = true;
    },
    
    handleReviewModalOk() {
      if (this.reviewAction === 'reject') {
        this.reviewForm.validateFields((err, values) => {
          if (!err) {
            // 模拟拒绝操作
            const index = this.reviewData.findIndex(item => item.id === this.currentApplication.id);
            if (index !== -1) {
              this.reviewData[index].status = 'rejected';
              // 同步更新申请状态列表
              const statusIndex = this.statusData.findIndex(item => 
                item.courseName === this.currentApplication.courseName && 
                item.applyTime === this.currentApplication.applyTime
              );
              if (statusIndex !== -1) {
                this.statusData[statusIndex].status = 'rejected';
                this.statusData[statusIndex].rejectReason = values.rejectReason;
              }
            }
            this.$message.success('已拒绝该申请');
            this.reviewModalVisible = false;
          }
        });
      } else if (this.reviewAction === 'approve') {
        // 模拟通过操作
        const index = this.reviewData.findIndex(item => item.id === this.currentApplication.id);
        if (index !== -1) {
          this.reviewData[index].status = 'approved';
          // 同步更新申请状态列表
          const statusIndex = this.statusData.findIndex(item => 
            item.courseName === this.currentApplication.courseName && 
            item.applyTime === this.currentApplication.applyTime
          );
          if (statusIndex !== -1) {
            this.statusData[statusIndex].status = 'approved';
          }
        }
        this.$message.success('已通过该申请');
        this.reviewModalVisible = false;
      } else {
        // 只是查看详情
        this.reviewModalVisible = false;
      }
    },
    
    handleReviewModalCancel() {
      this.reviewModalVisible = false;
    },
    
    getCourseName(courseCode) {
      const courses = {
        'cs101': '计算机科学导论 (CS101)',
        'math201': '高等数学（上）	 (MATH201)',
        'phy301': '量子力学 (PHY301)',
        'chem401': '有机化学 (CHEM401)',
        'lit501': '现代文学 (LIT501)',
      };
      return courses[courseCode] || courseCode;
    },
  },
};
</script>

<style scoped>
.course-qualification-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tab-content {
  padding: 20px;
}

.ant-form-item {
  margin-bottom: 16px;
}
</style>